import Cookie from 'vue-cookie';

/**
 * 时间格式转换 ms -> date
 * @return {string} yyyy-MM-dd hh:mm:ss格式时间
 */
const msToDate = (_ms, _format) => {
  let ms = _ms;
  let format = _format;
  if (ms.toString().length === 10) {
    ms *= 1000;
  }
  format = format || 'yyyy-MM-dd hh:mm:ss';
  const d = new Date(ms);
  const year = d.getFullYear();
  const month = d.getMonth() + 1;
  const day = d.getDate();
  const hour = d.getHours();
  const minute = d.getMinutes();
  const seconds = d.getSeconds();

  const addPrefix = source => (source < 10 ? `0${source}` : source);

  format = format.replace('yyyy', year)
    .replace('MM', addPrefix(month))
    .replace('dd', addPrefix(day))
    .replace('hh', addPrefix(hour))
    .replace('mm', addPrefix(minute))
    .replace('ss', addPrefix(seconds));

  return format;
};

/**
 * 时间格式转换 ms -> date
 * @return {string} yyyy-MM-dd hh:mm:ss格式时间
 */
exports.nowToDate = _format => {
  let format = _format;
  format = format || 'yyyy-MM-dd hh:mm:ss';
  return msToDate(new Date().getTime(), format);
};

/**
 * 过去距离当前时间差
 * @param  {int} ms 毫秒数
 * @return {string}    时间差标示
 */
exports.dateFromNow = ms => {
  const time = parseFloat(ms) / 1000;
  let result = '';
  if (time) {
    if (time > 60 && time < 3600) {
      result = `${parseInt(time / 60.0, 10)}分钟前`;
    } else if (time >= 3600 && time < 24 * 3600) {
      result = `${parseInt(time / 3600.0, 10)}小时前`;
    } else if (time >= 24 * 3600 && time < 30 * 24 * 3600) {
      result = `${parseInt(time / 3600.0 / 24.0, 10)}天前`;
    } else if (time >= 30 * 24 * 3600 && time < 12 * 30 * 24 * 3600) {
      result = `${parseInt(time / 3600.0 / 24.0 / 30, 10)}月前`;
    } else if (time >= 12 * 30 * 24 * 3600) {
      result = `${parseInt(time / 3600.0 / 24.0 / 30.0 / 12.0, 10)}年前`;
    } else {
      result = `${parseInt(time / 1.0, 10)}秒前`;
    }
  }

  return result;
};

/**
 * JS生成随机的由字母数字组合的字符串
 * @param  {boolean} flag 是否范围浮动
 * @param  {number}  min  最小值
 * @param  {number}  max  最大值
 * @return {string}       生成的随机字串
 */
exports.randomName = (flag, min, max) => {
  const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  let str = '';
  let range = min;
  let pos = 0;
  if (flag) {
    range = Math.round(Math.random() * (max - min)) + min;
  }
  for (let i = 0; i < range; i++) {
    pos = Math.round(Math.random() * (arr.length - 1));
    str += arr[pos];
  }
  return str;
};

/**
 * object转成uri参数字符串
 * @param  {object} obj object格式数据 { x: xx, y: yy }
 * @return {string}     uri参数字串 x=xx&y=yy
 */
exports.obj2uri = obj => Object.keys(obj).map(k => `${k}=${obj[k]}`).join('&');

/**
 * 身份转换
 * @param  {int}    num   身份模式编号
 * @return {string}       身份字符串
 */
exports.num2mode = num => {
  let mode = '';
  switch (num) {
    case 0:
      mode = '经期';
      break;
    case 1:
      mode = '怀孕';
      break;
    case 2:
      mode = '备孕';
      break;
    case 3:
      mode = '辣妈';
      break;
    default:
      mode = '经期';
      break;
  }
  return mode;
};

/**
 * 返回顶部
 * @return {}
 */
exports.toTop = () => {
  window.scrollTo(0, 0);
};

/**
 * 审核状态转换
 * @param  {int}  num   审核状态参数
 * @return {string}     审核状态
 */
exports.status2str = num => {
  let status = '';
  switch (parseInt(num, 10)) {
    case 1:
      status = '审核通过';
      break;
    case 2:
      status = '未通过审核';
      break;
    case 3:
    case 4:
    case 5:
      status = '账号审核中';
      break;
    default:
      status = '';
      break;
  }
  return status;
};

exports.rssNum2Status = num => {
  let status = '';
  switch (parseInt(num, 10)) {
    case 0:
      status = '待审核';
      break;
    case 1:
      status = '审核通过';
      break;
    case 2:
      status = '未通过审核';
      break;
    case 3:
      status = '删除';
      break;
    case 4:
      status = '已停用';
      break;
    default:
      status = '';
      break;
  }
  return status;
};

exports.noEnterReturn = val => val.trim().replace(/[\r\n]/g, '');

exports.text2html = val => val.trim().replace(/\r\n/g, '<br />').replace(/\n/g, '<br />').replace(/\r/g, '<br />');

/**
 * 非法状态拦截
 * @param  {int}      status   状态值
 * @param  {function} msg      Message函数
 * @param  {this}     self     this or next
 * @param  {string}   type     'index' or 'publish'
 * @return {null}              弹框提示
 */
exports.statusWarning = (status, msg, self, type) => {
  if (status === 3 || status === 4 || status === 5) {
    msg({
      showClose: true,
      message: '您的账号正在审核中，目前还不能发表文章哦，体验下其他功能吧！',
      type: 'info'
    });
    return;
  }
  if (status === 2) {
    msg({
      showClose: true,
      message: '您的账号未通过审核，赶紧去修改您的账号信息吧~',
      type: 'info'
    });
    return;
  }
  if (status === 6) {
    msg({
      showClose: true,
      message: '您的账号已被停用，无法进行发文及回复操作！',
      type: 'info'
    });
    return;
  }
  if (status === 1 && type === 'index') {
    self.$router.push({ path: '/home/publish/2' });
  }
  if (status === 1 && type === 'publish') {
    self();
  }
};

/**
 * 根据不同的环境返回sso地址
 * @return {string} sso地址
 */
const getSSOAddr = () => {
  const host = window.location.host;
  let ssoApi = 'https://test-sso.my.com/sso/';
  if (host.indexOf('test-') > -1 || host.indexOf('pc-') > -1 || host.indexOf('localhost') > -1 || host.indexOf('127.0.0.1') > -1) {
    ssoApi = 'https://test-sso.my.com/sso/';
  } else if (host.indexOf('yf-') > -1) {
    ssoApi = 'https://yf-sso.my.com/sso/';
  } else {
    ssoApi = 'https://sso.my.com/sso/';
  }
  return ssoApi;
};

/**
 * 根据不同的环境返回mp地址
 * @return {string} mp地址
 */
const getMPAddr = () => {
  const host = window.location.host;
  let mpApi = 'https://test-mp.my.com';
  if (host.indexOf('pc-') > -1 || host.indexOf('localhost') > -1 || host.indexOf('127.0.0.1') > -1) {
    mpApi = 'http://pc-mp.my.com:8888/';
  } else if (host.indexOf('test-') > -1) {
    mpApi = 'https://test-mp.my.com';
  } else if (host.indexOf('yf-') > -1) {
    mpApi = 'https://yf-mp.my.com';
  } else {
    mpApi = 'https://mp.my.com';
  }
  return mpApi;
};

/**
 * 根据不同的环境返回news地址
 * @return {string} news地址
 */
exports.getNewsAddr = () => {
  const host = window.location.host;
  let newsApi = 'https://test-news-node.my.com';
  if (host.indexOf('test-') > -1 || host.indexOf('pc-') > -1 || host.indexOf('localhost') > -1 || host.indexOf('127.0.0.1') > -1) {
    newsApi = 'https://test-news-node.my.com';
  } else if (host.indexOf('yf-') > -1) {
    newsApi = 'https://yf-news-node.my.com';
  } else {
    newsApi = 'https://news-node.my.com';
  }
  return newsApi;
};

/**
 * 根据不同的环境返回login地址
 * @return {string} login地址
 */
exports.getLoginAddr = () => `${getSSOAddr()}login?callback_url=${getMPAddr()}?client_id=K17npO82`;

/**
 * 根据不同的环境返回回调为当前地址的登录地址
 * @return {string} 登录地址
 */
exports.getCallbackAddr = () => `${getSSOAddr()}login?callback_url=${window.location.href}?client_id=K17npO82`;

/**
 * 读取cookie，判断是否登录
 * @return {boolean} 是否登录
 */
exports.isLogin = () => {
  const loginStatus = +Cookie.get('webLoginStatus');
  const expireTime = +Cookie.get('expireTime');
  const time = expireTime - Date.parse(new Date()) / 1000;
  console.log('loginStatus: ', !!loginStatus, ' expireTime: ', time);
  if (!!loginStatus && loginStatus === 1 && expireTime && time > 0) {
    return true;
  }
  return false;
};

/**
 * 判断是否为IE9浏览器
 * @return {boolean}  true or false
 */
exports.isIE9 = () => {
  if (navigator.userAgent.toLowerCase().indexOf('msie 9.0') > 0) {
    return true;
  }
  return false;
};

/**
 * 判断是否符合标签规则
 * @param  {string}  value 标签
 * @return {boolean}       true or false
 */
exports.isTag = value => /[A-Za-z0-9\u4e00-\u9fa5]/g.test(value);

/**
 * 判断是否符合微信号规则
 * @param  {string}  value 微信号
 * @return {boolean}       true or false
 */
exports.isWechat = value => /^[a-zA-Z\d_]{5,}$/.test(value);

/**
 * 判断是否符合URL规则
 * @param  {string}  value URL链接
 * @return {boolean}       true or false
 */
exports.isURL = value => /^(https?:\/\/(?:www\.|(?!www))[^\s.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})?$/ig.test(value);

/**
 * 判断是否符合密码规则
 * @param  {string} value 密码
 * @return {boolean}      true or false
 */
exports.isPass = value => /^(?![A-Za-z]+$)(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S{6,16}$/.test(value);

/**
 * 判断是否符合手机规则
 * @param  {string} value 手机
 * @return {boolean}      true or false
 */
const isMobile = exports.isMobile = value => /^1(3|4|5|7|8)\d{9}$/.test(value.trim());

/**
 * 判断是否符合邮箱规则
 * @param  {string} value 邮箱
 * @return {boolean}      true or false
 */
exports.isEmail = value => /^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.){1,4}[a-z]{2,3}$/.test(value.trim());

/**
 * 判断是否是数字
 * @param  {string} value 输入值
 * @return {boolean}      true or false
 */
exports.isNum = value => /^[0-9]*$/.test(value.trim());

/**
 * 判断是否是整形数据
 * @param  {string} value 输入值
 * @return {boolean}      true or false
 */
exports.isInteger = value => Number.isInteger(parseInt(value.trim(), 10));

/**
 * 判断是否是身份证号 15位到18位的身份证号码正则
 * @param  {string} value 身份证号
 * @return {boolean}      true or false
 */
exports.isIdCard = value => /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|[Xx])$/.test(value.trim());

/**
 * 判断是否是中文名字 至少2个中文字符
 * @param  {string} value 名字
 * @return {boolean}      true or false
 */
exports.isChineseName = value => /^[\u4E00-\u9FA5]{2,15}$/.test(value.trim());

/**
 * 判断
 * @param  {[type]} value [description]
 * @return {[type]}       [description]
 */
exports.ismyName = value => /^[\u4e00-\u9fa5a-zA-Z\d_]*$/gi.test(value.trim());

/**
 * 返回默认头像
 * @return {string} 头像base64格式
 */
const getAvatar = () => '';

exports.getArticleDefaultCover = () => '';

exports.getVIPIdCardPic = () => '';

/**
 * 兼容https/http
 * @param  {string} value 地址
 * @return {string}       替换后的地址
 */
exports.https = value => {
  if (value) {
    return value.replace(/^http(s)?:/gi, '');
  }
  return '';
};

const setUserPhone = exports.setUserPhone = user => {
  if (user && Object.prototype.hasOwnProperty.call(user, 'phone')) {
    Cookie.set('my_mp_phone', user.phone, { expires: 7, domain: '.my.com' });
  }
};

const setUserStatus = exports.setUserStatus = user => {
  if (user && Object.prototype.hasOwnProperty.call(user, 'status')) {
    Cookie.set('my_mp_status', user.status, { expires: 7, domain: '.my.com' });
  } else {
    Cookie.set('my_mp_status', user, { expires: 7, domain: '.my.com' });
  }
};

const setUserType = exports.setUserType = user => {
  if (user && Object.prototype.hasOwnProperty.call(user, 'type')) {
    Cookie.set('my_mp_type', user.type, { expires: 7, domain: '.my.com' });
  }
};

const setUserVerified = exports.setUserVerified = user => {
  if (user && Object.prototype.hasOwnProperty.call(user, 'phone_verified')) {
    Cookie.set('my_mp_verified', user.phone_verified, { expires: 7, domain: '.my.com' });
  }
};

const setUserName = exports.setUserName = user => {
  if (user && Object.prototype.hasOwnProperty.call(user, 'name')) {
    Cookie.set('my_mp_name', user.name, { expires: 7, domain: '.my.com' });
  }
};

const setUserAvatar = exports.setUserAvatar = user => {
  if (user && Object.prototype.hasOwnProperty.call(user, 'avatar')) {
    Cookie.set('my_mp_avatar', user.avatar, { expires: 7, domain: '.my.com' });
  }
};

exports.setUserInfo = user => {
  setUserPhone(user);
  setUserStatus(user);
  setUserType(user);
  setUserVerified(user);
  setUserName(user);
  setUserAvatar(user);
};

const hidMobile = value => {
  if (value) {
    return value.trim().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
  }
  return '';
};

exports.getUserAvatar = () => {
  const mpAvatar = Cookie.get('my_mp_avatar');
  if (mpAvatar) {
    return mpAvatar + '?time=' + Date.now();
  }
  return getAvatar();
};

exports.getUserName = () => {
  const mpName = Cookie.get('my_mp_name');
  const mpPhone = Cookie.get('my_mp_phone');
  if (mpName) {
    return mpName;
  } else if (mpPhone && isMobile(mpPhone)) {
    return hidMobile(mpPhone);
  }
  return '';
};

exports.getUserVerified = () => +Cookie.get('my_mp_verified') || 0;

exports.getUserType = () => +Cookie.get('my_mp_type') || 1;

exports.getUserStatus = () => +Cookie.get('my_mp_status') || 0;

exports.getUserPhone = () => Cookie.get('my_mp_phone') || '';

exports.getAvatar = getAvatar;
exports.getSSOAddr = getSSOAddr;
exports.getMPAddr = getMPAddr;
exports.setUserStatus = setUserStatus;
exports.msToDate = msToDate;
